#include "bs_app.h"
#include "bffs.h"
#include "fdiskio.h"
#define LOG_TAG        "[fs"
#include "log.h"

#define BFFS_FAT_SIZE         1
#if _FS_REENTRANT
#define    ENTER_FF(fs)        { if (!lock_fs(fs)) return FR_TIMEOUT; }
#define    LEAVE_FF(fs, res)    { unlock_fs(fs, res); return res; }

#else
#define    ENTER_FF(fs)
#define    LEAVE_FF(fs, res)    return res

#endif

#define    ABORT(fs, res)        { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }

#ifndef    NULL
#define    NULL    0
#endif

/* Name status flags */
#define NS             11        /* Offset of name status byte */
#define NS_LOSS        0x01    /* Out of 8.3 format */
#define NS_LFN         0x02    /* Force to create LFN entry */
#define NS_LAST        0x04    /* Last segment */
#define NS_BODY        0x08    /* Lower case flag (body) */
#define NS_EXT         0x10    /* Lower case flag (ext) */
#define NS_DOT         0x20    /* Dot entry */


//static
FATFS *FatFs[_DRIVES];    /* Pointer to the file system objects (logical drives) */

JF_FILE journal_file;
#define INITBUF(dj)         BYTE __sp[12];\
                            dj.fn = __sp;

FRESULT chk_mounted (const CHAR **path, FATFS **rfs);


/*-----------------------------------------------------------------------*/
/* crc32 functions                                                      */
/*-----------------------------------------------------------------------*/
static const uint32_t bffs_crc32tab[16] = {
   0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190,
   0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344,
   0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278,
   0xbdbdf21c
};


/*!
    \brief 计算crc
    \param[in]  data: 起始地址
    \param[in]  length: 长度
    \param[in]  crc: 初值
    \param[out] none
    \retval 0: successful，1：failed
*/
static uint32_t bffs_crc32(const void *data, unsigned int length, uint32_t crc)
{
   const unsigned char *buf = (const unsigned char *)data;
   unsigned int i;

   for (i = 0; i < length; ++i)
   {
      crc ^= buf[i];
      crc = bffs_crc32tab[crc & 0x0f] ^ (crc >> 4);
      crc = bffs_crc32tab[crc & 0x0f] ^ (crc >> 4);
   }

   return crc;
}


/*-----------------------------------------------------------------------*/
/* String functions                                                      */
/*-----------------------------------------------------------------------*/

/* Copy memory to memory */
static
void mem_cpy (void* dst, const void* src, int cnt) {
    char *d = (char*)dst;
    const char *s = (const char *)src;
    while (cnt--) *d++ = *s++;
}

/* Fill memory */
static
void mem_set (void* dst, int val, int cnt) {
    char *d = (char*)dst;
    while (cnt--) *d++ = (char)val;
}

/* Compare memory to memory */
static
int mem_cmp (const void* dst, const void* src, int cnt) {
    const char *d = (const char *)dst, *s = (const char *)src;
    int r = 0;
    while (cnt-- && (r = *d++ - *s++) == 0) ;
    return r;
}

/* Check if chr is contained in the string */
// static
// int chk_chr (const char* str, int chr) {
//     while (*str && *str != chr) str++;
//     return *str;
// }


// 目录项
// 0xFF 未使用
// 0x00 已删除


// next prev
// FFFF xxxx 结束簇
// 0000 xxxx 开始簇
// FFFF FFFF 空闲簇

// 
/*-----------------------------------------------------------------------*/
/* Change window offset                                                  */
/*-----------------------------------------------------------------------*/

static
FRESULT move_window (
    FATFS *fs,        /* File system object */
    DWORD sector    /* Sector number to make appearance in the fs->win[] */
)                    /* Move to zero only writes back dirty window */
{
    DWORD wsect;
    BYTE  n_copy, n_sectors;
    uint32_t crc32_val;

    wsect = fs->winsect;
    if (wsect != sector) {    /* Changed current window */
        if (fs->wflag) {      /* Write back dirty window if needed */
            if (wsect == fs->dirbase) {
                crc32_val = bffs_crc32(fs->win, SS(fs)-4, 0);
                ST_DWORD(&fs->win[SS(fs)-4], crc32_val);

                n_sectors = 1;
                n_copy = 2;
            } else if (wsect == fs->fatbase) {
                // 法二：TODO 再开辟一个 4kB 的都缓存区
                crc32_val = bffs_crc32(fs->win, SS(fs)-4, 0);
                ST_DWORD(&fs->win[SS(fs)-4], crc32_val);

                n_sectors = fs->sects_fat;
                n_copy = fs->n_fats;
            } else
                n_copy = 0;

            if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK)
                return FR_DISK_ERR;
            
            fs->wflag = 0;
            if (n_copy > 0) {    /* In FAT area */
                BYTE nf;
                for (nf = n_copy; nf > 1; nf--) {       /* Reflect the change to all FAT copies */
                    wsect += n_sectors;
                    disk_write(fs->drive, fs->win, wsect, 1);
                }
            }
        }
        if (sector) {
            if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK)
                return FR_DISK_ERR;
            fs->winsect = sector;
        }
    }
    return FR_OK;
}




/*-----------------------------------------------------------------------*/
/* Clean-up cached data                                                  */
/*-----------------------------------------------------------------------*/
static
FRESULT sync (    /* FR_OK: successful, FR_DISK_ERR: failed */
    FATFS *fs    /* File system object */
)
{
    FRESULT res;

    res = move_window(fs, 0);
    if (res == FR_OK) {
        /* Make sure that no pending write process in the physical drive */
        if (disk_ioctl(fs->drive, CTRL_SYNC, (void*)NULL) != RES_OK)
            res = FR_DISK_ERR;
    }
    return res;
}




/*-----------------------------------------------------------------------*/
/* FAT access - Read value of a FAT entry                                */
/*-----------------------------------------------------------------------*/


DWORD get_fat (    /* 0:Disk error, Else:Cluster status */
    FATFS *fs,    /* File system object */
    DWORD clst    /* Cluster# to get the link information */
)
{
    DWORD fsect;

    if (clst < 1 || clst >= fs->max_clust)    /* Range check */
        return 0;
    
    fsect = fs->fatbase;
    if (move_window(fs, fsect + (clst / (SS(fs) / 4)))) return 1;
        return LD_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)]);
}




/*-----------------------------------------------------------------------*/
/* FAT access - Change value of a FAT entry                              */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY

FRESULT put_fat (
    FATFS *fs,    /* File system object */
    DWORD clst,    /* Cluster# to be changed in range of 2 to fs->max_clust - 1 */
    DWORD val    /* New value to mark the cluster */
)
{
    DWORD fsect;
    FRESULT res;

    if (clst < 1 || clst >= fs->max_clust) {    /* Range check */
        res = FR_INT_ERR;
    } else {
        fsect = fs->fatbase;
        res = move_window(fs, fsect + (clst / (SS(fs) / 4)));
        if (res != FR_OK) return res;
        ST_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)], val);
    }
    fs->wflag = 1;
    return res;
}
#endif /* !_FS_READONLY */




/*-----------------------------------------------------------------------*/
/* FAT handling - Remove a cluster chain                                 */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT remove_chain (
    FATFS *fs,            /* File system object */
    DWORD clst            /* Cluster# to remove a chain from */
)
{
    FRESULT res;
    DWORD nxt;

    if (clst < 1 || clst >= fs->max_clust) {    /* Check the range of cluster# */
        res = FR_INT_ERR;
    } else {
        res = FR_OK;
        while (clst < fs->max_clust) {                    /* Not a last link? */
            nxt = get_fat(fs, clst);                      /* Get cluster status */
            if (nxt == 0xFFFFFFFF) break;                  /* Empty cluster? */
            if (nxt == 0) { res = FR_DISK_ERR; break; }    /* Internal error? */
            res = put_fat(fs, clst, 0xFFFFFFFF);            /* Mark the cluster "empty" */
            if (res != FR_OK) break;
            clst = NEXT_CLST(nxt);    /* Next cluster */
        }
    }
    return res;
}
#endif



// TODO 注意这个函数的返回值，这个函数只能返回0(err) 和其它非零值
// return 1 是个正确的返回值
/*-----------------------------------------------------------------------*/
/* FAT handling - Stretch or Create a cluster chain                      */
/*-----------------------------------------------------------------------*/
static
DWORD create_chain (    /* 0:No free cluster, 0xFFFFFFFF:Disk error, >=2:New cluster# */
    FATFS *fs,            /* File system object */
    DWORD clst            /* Cluster# to stretch. 0 means create a new chain. */
)
{
    DWORD cs, ncl, scl, mcl;

    mcl = fs->max_clust;
    if (clst == 0) {                     /* Create new chain */
        scl = 0;
    }
    else {                               /* Stretch existing chain */
        cs = get_fat(fs, clst);          /* Check the cluster status */
        if (cs == 0) return 0xFFFFFFFF;  /* It is an invalid cluster */
        cs = NEXT_CLST(cs);
        if ( cs < mcl) return cs;        /* It is already followed by next cluster */
        scl = clst;
    }

    ncl = scl;                           /* Start cluster */
    for (;;) {
        ncl++;                           /* Next cluster */
        if (ncl >= mcl) {                /* Wrap around */
            ncl = 1;                     /* No free cluster */
        }
        cs = get_fat(fs, ncl);           /* Get the cluster status */
        if (cs == 0xFFFFFFFF) break;     /* Found a free cluster */
        if (cs == 0)                     /* An error occurred */
            return 0;
        if (ncl == scl) return 0;        /* No free cluster */
    }

    // 认为这是文件的最后一个簇；如果同时是第一个簇则 clst==0；
    if (put_fat(fs, ncl, NEW_CLST(clst, 0xFFFF)))    /* Mark the new cluster "in use" */
        return 0xFFFFFFFF;
    if (clst != 0) {                     /* Link it to the previous one if needed */
        cs = get_fat(fs, clst);
        if (put_fat(fs, clst, NEW_CLST(PREV_CLST(cs), ncl)))
            return 0xFFFFFFFF;
    }

    /* Update FSINFO */
    return ncl;                          /* Return new cluster number */
}




/*-----------------------------------------------------------------------*/
/* Get sector# from cluster#                                             */
/*-----------------------------------------------------------------------*/
// 只有在 read write 的时候才会判断它的返回值
DWORD clust2sect (    /* !=0: Sector number, 0: Failed - invalid cluster# */
    FATFS *fs,        /* File system object */
    DWORD clst        /* Cluster# to be converted */
)
{
    if (clst >= (fs->max_clust)) return 0;        /* Invalid cluster# */
    return clst * fs->csize + fs->database;
}




/*-----------------------------------------------------------------------*/
/* Directory handling - Seek directory index                             */
/*-----------------------------------------------------------------------*/
static
FRESULT dir_seek (
    DIR *dj,        /* Pointer to directory object */
    WORD idx        /* Directory index number */
)
{
    if (idx >= dj->fs->n_rootdir)        /* Index is out of range */
        return FR_INT_ERR;
    dj->index = idx;
    dj->sect = dj->fs->dirbase;                                /* Sector# */
    dj->dir = dj->fs->win + (idx % (SS(dj->fs) / 32)) * 32;    /* Ptr to the entry in the sector */
    return FR_OK;    /* Seek succeeded */
}




/*-----------------------------------------------------------------------*/
/* Directory handling - Move directory index next                        */
/*-----------------------------------------------------------------------*/
// 这里只有一层目录，不存在嵌套，所以直接下一条
static
FRESULT dir_next (    /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not streach */
    DIR *dj,         /* Pointer to directory object */
    bool streach     /* FALSE: Do not stretch table, TRUE: Stretch table if needed */
)
{   
	WORD i;
    (void)streach;

    i = dj->index + 1;
    if (i >= dj->fs->n_rootdir)        /* Index is out of range */
        return FR_NO_FILE;
    if (!i || !dj->sect)    /* Report EOT when index has reached 65535 */
        return FR_NO_FILE;

    dj->index = i;
    dj->dir = dj->fs->win + (i % (SS(dj->fs) / 32)) * 32;

    return FR_OK;
}



// 这里有可能新建目录吗
/*-----------------------------------------------------------------------*/
/* Directory handling - Find an object in the directory                  */
/*-----------------------------------------------------------------------*/
static
FRESULT dir_find (
    DIR *dj            /* Pointer to the directory object linked to the file name */
)
{
    FRESULT res;
    BYTE c, *dir;

    res = dir_seek(dj, 0);            /* Rewind directory object */
    if (res != FR_OK) return res;

    do {
        res = move_window(dj->fs, dj->sect);
        if (res != FR_OK) break;
        dir = dj->dir;                    /* Ptr to the directory entry of current index */
        c = dir[0];
        if (c == 0xFF) { res = FR_NO_FILE; break; }    /* Reached to end of table */

        // if (c == dj->fn[0]) /* Is it a valid entry? */
        if (!mem_cmp(dir, dj->fn, 8))
            break;
        res = dir_next(dj, FALSE);        /* Next entry */
    } while (res == FR_OK);

    return res;
}




/*-----------------------------------------------------------------------*/
/* Read an object from the directory                                     */
/*-----------------------------------------------------------------------*/
static
FRESULT dir_read (
    DIR *dj            /* Pointer to the directory object that pointing the entry to be read */
)
{
    FRESULT res;
    BYTE c, *dir;

    res = FR_NO_FILE;
    while (dj->sect) {
        res = move_window(dj->fs, dj->sect);
        if (res != FR_OK) break;
        dir = dj->dir;                    /* Ptr to the directory entry of current index */
        c = dir[0];
        if (c == 0xFF) { res = FR_NO_FILE; break; }    /* Reached to end of table */
        if (c != 0)    /* Is it a valid entry? */
            break;
        res = dir_next(dj, FALSE);                /* Next entry */
        if (res != FR_OK) break;
    }

    if (res != FR_OK) dj->sect = 0;

    return res;
}




// 这里的 dir 已经有哪些参数？当前扇区、文件名
// 目录信息是在内部flash保存的，所以这里不用保存？
// 暂时将信息保存到这里
/*-----------------------------------------------------------------------*/
/* Register an object to the directory                                   */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT dir_register (    /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
    DIR *dj                /* Target directory with object name to be created */
)
{
    FRESULT res;
    BYTE c, *dir;

    res = dir_seek(dj, 0);
    if (res == FR_OK) {
        do {    /* Find a blank entry for the SFN */
            res = move_window(dj->fs, dj->sect);
            if (res != FR_OK) break;
            c = *dj->dir;
            if (c == 0x00 || c == 0xFF) break;    /* Is it a blank entry? */
            res = dir_next(dj, TRUE);             /* Next entry with table streach */
        } while (res == FR_OK);
    }

    if (res == FR_OK) {
        res = move_window(dj->fs, dj->sect);
        if (res == FR_OK) {
            dir = dj->dir;
            mem_set(dir, 0, 32);         /* Clean the entry */
            mem_cpy(dir, dj->fn, 11);    /* Put SFN */
            dj->fs->wflag = 1;
        }
    }

    return res;
}
#endif /* !_FS_READONLY */




/*-----------------------------------------------------------------------*/
/* Remove an object from the directory                                   */
/*-----------------------------------------------------------------------*/
static
FRESULT dir_remove (    /* FR_OK: Successful, FR_DISK_ERR: A disk error */
    DIR *dj                /* Directory object pointing the entry to be removed */
)
{
    FRESULT res;
    res = dir_seek(dj, dj->index);
    if (res == FR_OK) {
        res = move_window(dj->fs, dj->sect);
        if (res == FR_OK) {
            *dj->dir = 0x00;            /* Mark the entry "deleted" */
            dj->fs->wflag = 1;
        }
    }
    return res;
}





// 这里需要给 dj 的某些字段赋值: 填充文件名
/*-----------------------------------------------------------------------*/
/* Follow a file path                                                    */
/*-----------------------------------------------------------------------*/

static
FRESULT follow_path (    /* FR_OK(0): successful, !=0: error code */
    DIR *dj,            /* Directory object to return last directory and found object */
    const CHAR *path    /* Full-path string to find a file or directory */
)
{
    FRESULT res;
    int i;
    const CHAR *p;

    while (*path == ' ') path++;    /* Skip leading spaces */
    /* no use */
    if ((UINT)*path < ' ') {            /* Null path means the start directory itself */
        res = dir_seek(dj, 0);
        dj->dir = NULL;
    } else {
        p = path;
        mem_set(dj->fn, 0, 12);
        for(i=0; i<8; i++) {
            if(p[i] != 0) dj->fn[i] = p[i];
        }
        res = dir_find(dj);
        // if (res != FR_OK) {                /* Could not find the object */
        //     if (res == FR_NO_FILE && !last)
        //         res = FR_NO_PATH;
        // }
    }
    return res;
}



/*-----------------------------------------------------------------------*/
/* Mount/Unmount a Logical Drive                                         */
/*-----------------------------------------------------------------------*/

FRESULT f_mount (
    BYTE vol,        /* Logical drive number to be mounted/unmounted */
    FATFS *fs        /* Pointer to new file system object (NULL for unmount)*/
)
{
    FATFS *rfs;
    const char *path = "0:\\";


    if (vol >= _DRIVES)                /* Check if the drive number is valid */
        return FR_INVALID_DRIVE;
    rfs = FatFs[vol];                /* Get current fs object */

    if (rfs) {
#if _FS_REENTRANT                    /* Discard sync object of the current volume */
        if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;
#endif
        rfs->fs_type = 0;            /* Clear old fs object */
    }

    if (fs) {
        fs->fs_type = 0;            /* Clear new fs object */
#if _FS_REENTRANT                    /* Create sync object for the new volume */
        if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;
#endif
    }
    FatFs[vol] = fs;                /* Register new fs object */
    chk_mounted(&path, NULL);
    return FR_OK;
}






/*-----------------------------------------------------------------------*/
/* Check if the file/dir object is valid or not                          */
/*-----------------------------------------------------------------------*/

static
FRESULT validate (    /* FR_OK(0): The object is valid, !=0: Invalid */
    FATFS *fs        /* Pointer to the file system object */
)
{
    if (!fs || fs->fs_type != 1)
        return FR_INVALID_OBJECT;

    ENTER_FF(fs);        /* Lock file system */
    return FR_OK;
}




/*-----------------------------------------------------------------------*/
/* Open or Create a File                                                 */
/*-----------------------------------------------------------------------*/

FRESULT f_open (
    FIL *fp,            /* Pointer to the blank file object */
    const CHAR *path,    /* Pointer to the file name */
    WORD mode            /* Access mode and file open mode flags */
)
{
    FRESULT res;
    DIR dj;
    BYTE *dir;

    fp->fs = NULL;        /* Clear file object */

    mode &= (FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW);
    res = chk_mounted(&path, &dj.fs);

    if (res != FR_OK) LEAVE_FF(dj.fs, res);
    INITBUF(dj);
    res = follow_path(&dj, path);    /* Follow the file path */

#if !_FS_READONLY
    /* Create or Open a file */
    if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
        DWORD ps, cl;

        if (res != FR_OK) {                       /* No file, create new */
            if (res == FR_NO_FILE)                /* There is no file to open, create a new entry */
                res = dir_register(&dj);
            // TODO , 这里很巧妙，直接退出
            if (res != FR_OK) LEAVE_FF(dj.fs, res);
            mode |= FA_CREATE_ALWAYS;
            // 这里只初始化了文件名，大小及其它参数都是0
            dir = dj.dir;                        /* Created entry (SFN entry) */
        }
        else {                                   /* Any object is already existing */
            if (mode & FA_CREATE_NEW)            /* Cannot create new */
                LEAVE_FF(dj.fs, FR_EXIST);
            dir = dj.dir;
            // if (!dir || (dir[DIR_Attr] & (AM_RDO | AM_DIR)))    /* Cannot overwrite it (R/O or DIR) */
            //     LEAVE_FF(dj.fs, FR_DENIED);
            if (mode & FA_CREATE_ALWAYS) {         /* Resize it to zero on over write mode */
                cl = LD_WORD(dir+DIR_FstClust);    /* Get start cluster */
                ST_WORD(dir+DIR_FstClust, 0);      /* cluster = 0 */
                ST_WORD(dir+DIR_TotClust, 0);
                ST_DWORD(dir+DIR_FileSize, 0);     /* size = 0 */
                dj.fs->wflag = 1;
                ps = dj.fs->winsect;               /* Remove the cluster chain */
                if (cl) {
                    res = remove_chain(dj.fs, cl);
                    if (res) LEAVE_FF(dj.fs, res);
                    // dj.fs->last_clust = cl - 1;  /* Reuse the cluster hole */
                }
                res = move_window(dj.fs, ps);
                if (res != FR_OK) LEAVE_FF(dj.fs, res);
            }
        }
        if (mode & FA_CREATE_ALWAYS) {
            // ps = get_fattime();
            // ST_DWORD(dir+DIR_CrtTime, ps);        /* Created time */
            // dj.fs->wflag = 1;
            mode |= FA__WRITTEN;                     /* Set file changed flag */
        }
    }
    /* Open an existing file */
    else {
#endif /* !_FS_READONLY */
        if (res != FR_OK) LEAVE_FF(dj.fs, res);       /* Follow failed */
        dir = dj.dir;
    }
    fp->dir_sect = dj.fs->winsect;        /* Pointer to the directory entry */
    fp->dir_ptr = dj.dir;

    fp->flag = mode;                                  /* File access mode */
    fp->org_clust = LD_WORD(dir+DIR_FstClust);        /* File start cluster */
    fp->fsize = LD_DWORD(dir+DIR_FileSize);;          /* File size */
    fp->fptr = 0; 
    fp->csect = 255;
    fp->dsect = 0;
    fp->fs = dj.fs;
    return FR_OK;
}





/*-----------------------------------------------------------------------*/
/* Open or Create a File                                                 */
/*-----------------------------------------------------------------------*/
// 如果当前目录项有效，则先解除fat链表，再写入；相当于覆盖
FRESULT f_create_by_index (
    FIL *fp,
    BYTE index,
    CHAR *dent,
    WORD guid
)
{
    FRESULT res;
    DIR dj;
    BYTE *dir, c;
    const CHAR *path;
    BYTE i;

    fp->fs = NULL;                                /* Clear file object */

    res = chk_mounted(&path, &dj.fs);

    if (res != FR_OK) LEAVE_FF(dj.fs, res);
    INITBUF(dj);
    
    /* copy filename */
    for (i=0; i<11 && dent[i] != 0; i++)
        dj.fn[i] = dent[i];
    for (; i<12 ;i++) dj.fn[i] = 0;

    res = dir_seek(&dj, index);                     /* Rewind directory object */
    if (res != FR_OK) return res;

    /* find directory entry */
    res = move_window(dj.fs, dj.sect);
    if (res != FR_OK) return res;
    dir = dj.dir;                                   /* Ptr to the directory entry of current index */
    c = dir[0];

    if (c == 0xFF || c==0x00) { res = FR_NO_FILE; }

    /* Create or Open a file */
    DWORD ps, cl;

    if (res != FR_OK) {
        /* There is no file to open, create a new entry */
        mem_set(dir, 0, 32);                         /* Clean the entry */
        
        ST_WORD(dir+DIR_UID, guid);
        mem_cpy(dir, dj.fn, 12);                     /* Put SFN */
        dj.fs->wflag = 1;
    }
    else {                                          /* Any object is already existing */
        // if (mode & FA_CREATE_ALWAYS) {           /* Resize it to zero on over write mode */
        cl = LD_WORD(dir+DIR_FstClust);             /* Get start cluster */
        ST_WORD(dir+DIR_FstClust, 0);               /* cluster = 0 */
        ST_WORD(dir+DIR_TotClust, 0);
        ST_DWORD(dir+DIR_FileSize, 0);              /* size = 0 */
        
        ST_WORD(dir+DIR_UID, guid);
        mem_cpy(dir, dj.fn, 12);                     /* Put SFN */
        dj.fs->wflag = 1;
        ps = dj.fs->winsect;                        /* Remove the cluster chain */
        if (cl) {
            res = remove_chain(dj.fs, cl);
            if (res) LEAVE_FF(dj.fs, res);
        }
        res = move_window(dj.fs, ps);
        if (res != FR_OK) LEAVE_FF(dj.fs, res);
    }

    fp->dir_sect = dj.fs->winsect;                     /* Pointer to the directory entry */
    fp->dir_ptr = dj.dir;

    fp->flag = FA_WRITE|FA_CREATE_ALWAYS|FA__WRITTEN;  /* File access mode */
    fp->org_clust = LD_WORD(dir+DIR_FstClust);         /* File start cluster */
    fp->fsize = LD_DWORD(dir+DIR_FileSize);;           /* File size */
    fp->fptr = 0; 
    fp->csect = 255;
    fp->dsect = 0;
    fp->fs = dj.fs;
    return FR_OK;
}


/*-----------------------------------------------------------------------*/
/* Open or Create a File                                                 */
/*-----------------------------------------------------------------------*/
// win里面一定有数据，则直接移动目录项
FRESULT f_open_by_index (
    FIL *fp,            /* Pointer to the blank file object */
    BYTE index,
    WORD mode           /* Access mode and file open mode flags */
)
{
    FRESULT res;
    DIR dj;
    BYTE *dir, c;
    const CHAR *path;

    fp->fs = NULL;        /* Clear file object */

    mode &= (FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW | FA_EMPTY_ROOT);
    res = chk_mounted(&path, &dj.fs);

    if (res != FR_OK) LEAVE_FF(dj.fs, res);
    INITBUF(dj);
    
    mem_set(dj.fn, 0, 12);
    res = dir_seek(&dj, index);            /* Rewind directory object */
    if (res != FR_OK) return res;

    /* find directory entry */
    res = move_window(dj.fs, dj.sect);
    if (res != FR_OK) return res;
    dir = dj.dir;                    /* Ptr to the directory entry of current index */
    c = dir[0];

    if (c == 0xFF || c==0x00) { res = FR_NO_FILE; }

    /* Create or Open a file */
    if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
        DWORD ps, cl;

        if (res != FR_OK) {
            /* There is no file to open, create a new entry */
            // res = dir_register(&dj);
            mode |= FA_CREATE_ALWAYS;
            mem_set(dir, 0, 32);         /* Clean the entry */
            mem_cpy(dir, dj.fn, 11);     /* Put SFN */
            dj.fs->wflag = 1;
        }
        else {                                   /* Any object is already existing */
            if (mode & FA_CREATE_NEW)            /* Cannot create new */
                LEAVE_FF(dj.fs, FR_EXIST);
            dir = dj.dir;
            /* root directory is empty? */
            if (mode & FA_CREATE_ALWAYS) {         /* Resize it to zero on over write mode */
                if (mode & FA_EMPTY_ROOT) {
                    cl = LD_WORD(dir+DIR_FstClust);    /* Get start cluster */
                    ST_WORD(dir+DIR_FstClust, 0);      /* cluster = 0 */
                    ST_WORD(dir+DIR_TotClust, 0);
                    ST_DWORD(dir+DIR_FileSize, 0);     /* size = 0 */
                    dj.fs->wflag = 1;
                    ps = dj.fs->winsect;               /* Remove the cluster chain */
                    if (cl) {
                        res = remove_chain(dj.fs, cl);
                        if (res) LEAVE_FF(dj.fs, res);
                    }
                    res = move_window(dj.fs, ps);
                    if (res != FR_OK) LEAVE_FF(dj.fs, res);
                } else {
                    memmove(dj.fs->win+32, dj.fs->win, 32*15);
                    mem_set(dj.dir, 0, 32);
                    dj.fs->wflag = 1;
                }
            }
        }
        if (mode & FA_CREATE_ALWAYS) {
            mode |= FA__WRITTEN;                     /* Set file changed flag */
        }
    }
    /* Open an existing file */
    else {
        if (res != FR_OK) LEAVE_FF(dj.fs, res);       /* Follow failed */
        dir = dj.dir;
    }
    fp->dir_sect = dj.fs->winsect;                    /* Pointer to the directory entry */
    fp->dir_ptr = dj.dir;

    fp->flag = mode;                                  /* File access mode */
    fp->org_clust = LD_WORD(dir+DIR_FstClust);        /* File start cluster */
    fp->fsize = LD_DWORD(dir+DIR_FileSize);;          /* File size */
    fp->fptr = 0; 
    fp->csect = 255;
    fp->dsect = 0;
    fp->fs = dj.fs;
    return FR_OK;
}



/*-----------------------------------------------------------------------*/
/* Read File                                                             */
/*-----------------------------------------------------------------------*/
#define SBF(f)        1024
// #define SBF(f)           SS(f)
FRESULT f_read (
    FIL *fp,           /* Pointer to the file object */
    void *buff,        /* Pointer to data buffer */
    UINT btr,          /* Number of bytes to read */
    UINT *br           /* Pointer to number of bytes read */
)
{
    FRESULT res;
    DWORD clst, sect, remain;
    UINT rcnt, cc;
    BYTE *rbuff = buff;
    UINT count;
    if(br == NULL) br = &count;

    *br = 0;    /* Initialize bytes read */

    res = validate(fp->fs);                    /* Check validity of the object */
    if (res != FR_OK) LEAVE_FF(fp->fs, res);
    if (fp->flag & FA__ERROR)                        /* Check abort flag */
        LEAVE_FF(fp->fs, FR_INT_ERR);
    if (!(fp->flag & FA_READ))                         /* Check access mode */
        LEAVE_FF(fp->fs, FR_DENIED);
    remain = fp->fsize - fp->fptr;
    if (btr > remain) btr = (UINT)remain;            /* Truncate btr by remaining bytes */

    for ( ;  btr;                                    /* Repeat until all data transferred */
        rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
        if ((fp->fptr % SBF(fp)) == 0) {
        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */
            if (fp->csect >= fp->fs->csize) {        /* On the cluster boundary? */
                clst = (fp->fptr == 0) ?            /* On the top of the file? */
                    fp->org_clust : NEXT_CLST(get_fat(fp->fs, fp->curr_clust));
                if (clst == 0) ABORT(fp->fs, FR_INT_ERR);
                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
                fp->curr_clust = clst;                /* Update current cluster */
                fp->csect = 0;                        /* Reset sector offset in the cluster */
            }
            sect = clust2sect(fp->fs, fp->curr_clust);    /* Get current sector */
            if (!sect) ABORT(fp->fs, FR_INT_ERR);
            sect += fp->csect;
            cc = btr / SS(fp->fs);                    /* When remaining bytes >= sector size, */
            if (cc) {                                /* Read maximum contiguous sectors directly */
                // if (fp->csect + cc > fp->fs->csize)    /* Clip at cluster boundary */
                //     cc = fp->fs->csize - fp->csect;
                // if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK)
                //     ABORT(fp->fs, FR_DISK_ERR);
                // if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc)    /* Replace one of the read sectors with cached data if it contains a dirty sector */
                //     mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));
                // fp->csect += (BYTE)cc;                /* Next sector address in the cluster */
                // rcnt = SS(fp->fs) * cc;                /* Number of bytes transferred */
                // continue;
            }
            if (fp->flag & FA__DIRTY) {            /* Write sector I/O buffer if needed */
                if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
                    ABORT(fp->fs, FR_DISK_ERR);
                fp->flag &= ~FA__DIRTY;
            }
            if (fp->dsect != sect) {            /* Fill sector buffer with file data */
                // if (disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)
                //     ABORT(fp->fs, FR_DISK_ERR);
            }
            fp->dsect = sect;
            fp->csect++;                            /* Next sector address in the cluster */
        }
        if (disk_bread(fp->fs->drive, fp->buf, fp->dsect*SS(fp->fs) + fp->fptr % SS(fp->fs), SBF(fp)) != RES_OK)
            ABORT(fp->fs, FR_DISK_ERR);
        }
        rcnt = SBF(fp->fs) - (fp->fptr % SBF(fp->fs));    /* Get partial sector data from sector buffer */
        if (rcnt > btr) rcnt = btr;
        mem_cpy(rbuff, &fp->buf[fp->fptr % SBF(fp->fs)], rcnt);    /* Pick partial sector */
    }

    LEAVE_FF(fp->fs, FR_OK);
}




/*-----------------------------------------------------------------------*/
/* Write File                                                            */
/*-----------------------------------------------------------------------*/

FRESULT f_write (
    FIL *fp,            /* Pointer to the file object */
    const void *buff,    /* Pointer to the data to be written */
    UINT btw,            /* Number of bytes to write */
    UINT *bw            /* Pointer to number of bytes written */
)
{
    FRESULT res;
    DWORD clst, sect;
    UINT wcnt, cc;
    BYTE *wbuff = (BYTE *)buff;
    UINT written;
    if (bw==NULL) bw = &written;
    *bw = 0;    /* Initialize bytes written */

    res = validate(fp->fs);                    /* Check validity of the object */
    if (res != FR_OK) LEAVE_FF(fp->fs, res);
    if (fp->flag & FA__ERROR)                        /* Check abort flag */
        LEAVE_FF(fp->fs, FR_INT_ERR);
    if (!(fp->flag & FA_WRITE))                        /* Check access mode */
        LEAVE_FF(fp->fs, FR_DENIED);
    if (fp->fsize + btw < fp->fsize) btw = 0;        /* File size cannot reach 4GB */

    for ( ;  btw;                                    /* Repeat until all data transferred */
        wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */
            if (fp->csect >= fp->fs->csize) {        /* On the cluster boundary? */
                if (fp->fptr == 0) {                /* On the top of the file? */
                    clst = fp->org_clust;            /* Follow from the origin */
                    if (clst == 0)                    /* When there is no cluster chain, */
                        fp->org_clust = clst = create_chain(fp->fs, 0);    /* Create a new cluster chain */
                } else {                            /* Middle or end of the file */
                    clst = create_chain(fp->fs, fp->curr_clust);            /* Follow or stretch cluster chain */
                }
                // TODO 这里直接退出
                if (clst == 0) break;                /* Could not allocate a new cluster (disk full) */
                //if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
                fp->curr_clust = clst;                /* Update current cluster */
                fp->csect = 0;                        /* Reset sector address in the cluster */
            }
            if (fp->flag & FA__DIRTY) {        /* Write back data buffer prior to following direct transfer */
                if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
                    ABORT(fp->fs, FR_DISK_ERR);
                fp->flag &= ~FA__DIRTY;
            }
            sect = clust2sect(fp->fs, fp->curr_clust);    /* Get current sector */
            if (!sect) ABORT(fp->fs, FR_INT_ERR);
            // 切换下一个扇区：这个扇区还未使用
            sect += fp->csect;
            cc = btw / SS(fp->fs);                    /* When remaining bytes >= sector size, */
            if (cc) {                                /* Write maximum contiguous sectors directly */
                // TODO：暂未实现
                // if (fp->csect + cc > fp->fs->csize)    /* Clip at cluster boundary */
                //     cc = fp->fs->csize - fp->csect;
                // if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK)
                //     ABORT(fp->fs, FR_DISK_ERR);
                // if (fp->dsect - sect < cc) {        /* Refill sector cache if it gets dirty by the direct write */
                //     mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));
                //     fp->flag &= ~FA__DIRTY;
                // }
                // fp->csect += (BYTE)cc;                /* Next sector address in the cluster */
                // wcnt = SS(fp->fs) * cc;                /* Number of bytes transferred */
                // continue;
            }
            // TODO 这里决定是否需要更新数据。可能与 fseek 有关。
            if (fp->dsect != sect) {                /* Fill sector buffer with file data */
                if (fp->fptr < fp->fsize &&
                    disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)
                        ABORT(fp->fs, FR_DISK_ERR);
            }
            fp->dsect = sect;
            fp->csect++;                            /* Next sector address in the cluster */
        }
        wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Put partial sector into file I/O buffer */
        if (wcnt > btw) wcnt = btw;
        mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt);    /* Fit partial sector */
        fp->flag |= FA__DIRTY;
    }

    if (fp->fptr > fp->fsize) fp->fsize = fp->fptr;    /* Update file size if needed */
    fp->flag |= FA__WRITTEN;                        /* Set file changed flag */

    LEAVE_FF(fp->fs, FR_OK);
}




/*-----------------------------------------------------------------------*/
/* Synchronize the File Object                                           */
/*-----------------------------------------------------------------------*/

FRESULT f_sync (
    FIL *fp        /* Pointer to the file object */
)
{
    FRESULT res;
    //DWORD tim;
    BYTE *dir;

    res = validate(fp->fs);        /* Check validity of the object */
    if (res == FR_OK) {
        if (fp->flag & FA__WRITTEN) {    /* Has the file been written? */
            /* Write-back dirty buffer */
            if (fp->flag & FA__DIRTY) {
                if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
                    LEAVE_FF(fp->fs, FR_DISK_ERR);
                fp->flag &= ~FA__DIRTY;
            }
            /* Update the directory entry */
            res = move_window(fp->fs, fp->dir_sect);
            if (res == FR_OK) {
                dir = fp->dir_ptr;
                // dir[DIR_Attr] |= AM_ARC;                    /* Set archive bit */
                ST_DWORD(dir+DIR_FileSize, fp->fsize);        /* Update file size */
                ST_WORD(dir+DIR_FstClust, fp->org_clust);    /* Update start cluster */
                // tim = get_fattime();            /* Updated time */
                // ST_DWORD(dir+DIR_WrtTime, tim);
                fp->flag &= ~FA__WRITTEN;
                fp->fs->wflag = 1;
                res = sync(fp->fs);
            }
        }
    }
    LEAVE_FF(fp->fs, res);
}




/*-----------------------------------------------------------------------*/
/* Close File                                                            */
/*-----------------------------------------------------------------------*/

FRESULT f_close (
    FIL *fp        /* Pointer to the file object to be closed */
)
{
    FRESULT res;
    res = f_sync(fp);
    if (res == FR_OK) fp->fs = NULL;
    return res;
}




/*-----------------------------------------------------------------------*/
/* Seek File R/W Pointer                                                 */
/*-----------------------------------------------------------------------*/

FRESULT f_lseek (
    FIL *fp,        /* Pointer to the file object */
    DWORD ofs        /* File pointer from top of file */
)
{
    FRESULT res;
    DWORD clst, bcs, nsect, ifptr; /* nsect: new sect 定位后的新扇区*/

    res = validate(fp->fs);        /* Check validity of the object */
    if (res != FR_OK) LEAVE_FF(fp->fs, res);
    if (fp->flag & FA__ERROR)            /* Check abort flag */
        LEAVE_FF(fp->fs, FR_INT_ERR);
    if (ofs > fp->fsize                    /* In read-only mode, clip offset with the file size */
         && !(fp->flag & FA_WRITE)
        ) ofs = fp->fsize;

    ifptr = fp->fptr;
    fp->fptr = nsect = 0; fp->csect = 255;
    if (ofs > 0) {
        bcs = (DWORD)fp->fs->csize * SS(fp->fs);    /* Cluster size (byte) */
        if (ifptr > 0 &&
            (ofs - 1) / bcs >= (ifptr - 1) / bcs) {    /* When seek to same or following cluster, */
            fp->fptr = (ifptr - 1) & ~(bcs - 1);    /* start from the current cluster */
            ofs -= fp->fptr;
            clst = fp->curr_clust;
        } else {                                    /* When seek to back cluster, */
            clst = fp->org_clust;                    /* start from the first cluster */
#if !_FS_READONLY
            if (clst == 0) {                        /* If no cluster chain, create a new chain */
                clst = create_chain(fp->fs, 0);
                if (clst == 0) ABORT(fp->fs, FR_INT_ERR);
                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
                fp->org_clust = clst;
            }
#endif
            fp->curr_clust = clst;
        }
        if (clst != 0) {
            while (ofs > bcs) {                        /* Cluster following loop */
#if !_FS_READONLY
                if (fp->flag & FA_WRITE) {            /* Check if in write mode or not */
                    clst = create_chain(fp->fs, clst);    /* Force stretch if in write mode */
                    if (clst == 0) {                /* When disk gets full, clip file size */
                        ofs = bcs; break;
                    }
                } else
#endif
                    clst = NEXT_CLST(get_fat(fp->fs, clst));    /* Follow cluster chain if not in write mode */
                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
                if (clst == 0 || clst >= fp->fs->max_clust) ABORT(fp->fs, FR_INT_ERR);
                fp->curr_clust = clst;
                fp->fptr += bcs;
                ofs -= bcs;
            }
            fp->fptr += ofs;
            fp->csect = (BYTE)(ofs / SS(fp->fs));    /* Sector offset in the cluster */
            if (ofs % SS(fp->fs)) {
                nsect = clust2sect(fp->fs, clst);    /* Current sector */
                if (!nsect) ABORT(fp->fs, FR_INT_ERR);
                nsect += fp->csect;
                fp->csect++;
            }
        }
    }
    if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) {
#if !_FS_READONLY
        if (fp->flag & FA__DIRTY) {            /* Write-back dirty buffer if needed */
            if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
                ABORT(fp->fs, FR_DISK_ERR);
            fp->flag &= ~FA__DIRTY;
        }
#endif
        if (disk_read(fp->fs->drive, fp->buf, nsect, 1) != RES_OK)
            ABORT(fp->fs, FR_DISK_ERR);
        fp->dsect = nsect;
    }
#if !_FS_READONLY
    if (fp->fptr > fp->fsize) {            /* Set changed flag if the file size is extended */
        fp->fsize = fp->fptr;
        fp->flag |= FA__WRITTEN;
    }
#endif

    LEAVE_FF(fp->fs, res);
}





/*-----------------------------------------------------------------------*/
/* Delete a File or Directory                                            */
/*-----------------------------------------------------------------------*/

FRESULT f_unlink (
    const CHAR *path        /* Pointer to the file or directory path */
)
{
    FRESULT res;
    DIR dj;
    BYTE *dir;
    DWORD dclst;

    res = chk_mounted(&path, &dj.fs);
    if (res != FR_OK) LEAVE_FF(dj.fs, res);

    INITBUF(dj);
    res = follow_path(&dj, path);            /* Follow the file path */
    if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */

    dir = dj.dir;
    if (!dir)                                /* Is it the root directory? */
        LEAVE_FF(dj.fs, FR_INVALID_NAME);
    // if (dir[DIR_Attr] & AM_RDO)                /* Is it a R/O object? */
    //     LEAVE_FF(dj.fs, FR_DENIED);
    dclst = LD_WORD(dir+DIR_FstClust);

    res = dir_remove(&dj);                    /* Remove directory entry */
    if (res == FR_OK) {
        if (dclst)
            res = remove_chain(dj.fs, dclst);    /* Remove the cluster chain */
        if (res == FR_OK) res = sync(dj.fs);
    }

    LEAVE_FF(dj.fs, res);
}



/*-----------------------------------------------------------------------*/
/* Delete a File or Directory                                            */
/*-----------------------------------------------------------------------*/

FRESULT f_unlink_by_index (
    BYTE cur_index,
    BYTE max_index        /* Pointer to the file or directory path */
)
{
    FRESULT res;
    DIR dj;
    BYTE *dir;
    DWORD dclst;
    const CHAR* path;

    res = chk_mounted(&path, &dj.fs);
    if (res != FR_OK) LEAVE_FF(dj.fs, res);

    INITBUF(dj);
    // res = follow_path(&dj, path);            /* Follow the file path */
    dir_seek(&dj, cur_index);
    if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */

    res = move_window(dj.fs, dj.sect);
    if (res != FR_OK) return res;
    dir = dj.dir;
    if (!dir)                                /* Is it the root directory? */
        LEAVE_FF(dj.fs, FR_INVALID_NAME);
    // if (dir[DIR_Attr] & AM_RDO)                /* Is it a R/O object? */
    //     LEAVE_FF(dj.fs, FR_DENIED);
    dclst = LD_WORD(dir+DIR_FstClust);

    res = dir_remove(&dj);                    /* Remove directory entry */
    /* adjust directory entry */
    if (max_index >=1 && cur_index != max_index) {
        memmove(dj.dir, dj.dir+32, (max_index-cur_index)*32);
    }
    dir_seek(&dj, max_index);
    *dj.dir = 0;

    if (res == FR_OK) {
        if (dclst)
            res = remove_chain(dj.fs, dclst);    /* Remove the cluster chain */
        if (res == FR_OK) res = sync(dj.fs);
    }

    LEAVE_FF(dj.fs, res);
}





/*-----------------------------------------------------------------------*/
/* Read Directory Entry in Sequense                                      */
/*-----------------------------------------------------------------------*/

FRESULT f_readdir (
    DIR *dj,            /* Pointer to the open directory object */
    FILINFO *fno        /* Pointer to file information to return */
)
{
    FRESULT res;


    res = validate(dj->fs);            /* Check validity of the object */
    if (res == FR_OK) {
        INITBUF((*dj));
        if (!fno) {
            res = dir_seek(dj, 0);
        } else {
            res = dir_read(dj);
            if (res == FR_NO_FILE) {
                dj->sect = 0;
                res = FR_OK;
            }
            if (res == FR_OK) {                /* A valid entry is found */
                // get_fileinfo(dj, fno);        /* Get the object information */
                res = dir_next(dj, FALSE);    /* Increment index for next */
                if (res == FR_NO_FILE) {
                    dj->sect = 0;
                    res = FR_OK;
                }
            }
        }
    }

    LEAVE_FF(dj->fs, res);
}




/*-----------------------------------------------------------------------*/
/* Get Number of Free Clusters                                           */
/*-----------------------------------------------------------------------*/

FRESULT f_getfree (
    const CHAR *path,    /* Pointer to the logical drive number (root dir) */
    DWORD *nclst        /* Pointer to the variable to return number of free clusters */
)
{
    FRESULT res;
    DWORD n, clst, sect;
    UINT i;
    BYTE *p;
    FATFS *fs;

    /* Get drive number */
    res = chk_mounted(&path, &fs);
    if (res != FR_OK) LEAVE_FF(*fs, res);

    /* Get number of free clusters */
    clst = fs->max_clust;
    sect = fs->fatbase;
    i = 0; p = 0; n = 0;
    do {
        if (!i) {
            // 切换到下一个扇区
            res = move_window(fs, sect++);
            if (res != FR_OK)
                LEAVE_FF(*fs, res);
            p = fs->win;
            i = SS(fs);
        }
        if (LD_DWORD(p) == 0xFFFFFFFF) n++;
        p += 4; i -= 4;
    } while (--clst);

    *nclst = n;
    LEAVE_FF(fs, FR_OK);
}




/*-----------------------------------------------------------------------*/
/* Delete Journal File Content                                           */
/*-----------------------------------------------------------------------*/
FRESULT jf_delete()
{
    JF_FILE           *fp = &journal_file;
    // 参数检查
    if(fp->first_sect - fp->bmp_base != 2 || fp->bmp_base < 64) return FR_INVALID_OBJECT;
    /* Initialize first journal sector */
    if (disk_eraser(0, fp->first_sect) != RES_OK)
        return FR_DISK_ERR;

    /* Initialize bitmap sector */
    if (disk_eraser(0, fp->bmp_base) != RES_OK)
        return FR_DISK_ERR;

    /* Initialize bitmap sector */
    if (disk_eraser(0, fp->bmp_base+1) != RES_OK)
        return FR_DISK_ERR;

    if (disk_ioctl(0, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;
    fp->fptr = 0;
    fp->ofs_sect = 0;
    fp->flag = 0;
    return FR_OK;
}




/*-----------------------------------------------------------------------*/
/* Write Journal File                                                    */
/*-----------------------------------------------------------------------*/
#define EXT_SECT_SIZE    4096
FRESULT jf_write(const void *buff, uint32_t btw)
{
    JF_FILE           *fp = &journal_file;
    uint32_t           bm_pos = fp->fptr % 4 * 2;
    uint32_t           csect, wcnt, waddr;
    uint32_t           bmp_addr = 0;
    const uint32_t     sect_size = EXT_SECT_SIZE;
    uint8_t            wb, rb;
    uint8_t            *wbuff = (uint8_t *)buff;

    if(fp->first_sect - fp->bmp_base != 2 || fp->bmp_base < 64) return FR_INVALID_OBJECT;

    for( ; btw; wbuff+=wcnt, fp->fptr+=wcnt, btw-=wcnt) {
        if (fp->fptr % sect_size == 0) {
            if(fp->fptr != 0) fp->ofs_sect++;
            csect = fp->ofs_sect + fp->first_sect;
            if (csect >= fp->last_sect) {
                /* rewind first sector of current partition */
                csect = fp->first_sect;
                fp->ofs_sect = 0;
                fp->fptr = 0;
                /* Erase the first data sector */
                if (disk_eraser(0, csect) != RES_OK)
                    return FR_DISK_ERR;
                /* Erase the bitmap sector */
                if (disk_eraser(0, fp->bmp_base) != RES_OK)
                    return FR_DISK_ERR;
                if (disk_eraser(0, fp->bmp_base+1) != RES_OK)
                    return FR_DISK_ERR;
            }

            /* Erase the current data sector */
            if (csect != fp->first_sect) {
                if (disk_eraser(0, csect) != RES_OK)
                    return FR_DISK_ERR;
            }
            
            /* look up free sector bitmap */
            bm_pos = fp->ofs_sect % 4 * 2;
            bmp_addr = fp->bmp_base * sect_size + fp->ofs_sect/4;
            /* write bitmap sector */
            wb = (0x03<<bm_pos) ^ 0xFFFFFFFF;
            disk_bwrite(0, &wb, bmp_addr, 1);
            /* check readback */
            disk_bread(0, &rb, bmp_addr, 1);
            if ((rb & (0x03<<bm_pos)) != 0) {
                __NOP();
            }
            /* write backup bitmap sector */
            // TODO
        }
        waddr = (fp->first_sect + fp->ofs_sect)*sect_size + fp->fptr % sect_size;
        wcnt = sect_size - (fp->fptr % sect_size);
        if (wcnt > btw) wcnt = btw;
        disk_bwrite(0, wbuff, waddr, wcnt);
    }

    return FR_OK;
}




/*-----------------------------------------------------------------------*/
/* Create File System on the Drive                                       */
/*-----------------------------------------------------------------------*/
#define N_ROOTDIR     32             /* Multiple of 32 and <= 2048 */
#define N_FATS        2              /* 1 or 2 */
#define MAX_SECTOR    (65530*16)     /* Maximum partition size */
#define MIN_SECTOR    100UL         /* Minimum partition size */

FRESULT f_mkfs (
    BYTE drv            /* Logical drive number */
)
{
    BYTE m, *tbl;
    DWORD b_fat, b_dir, b_bmp, b_data;
    DWORD n_part, n_fat;
    DWORD n;
    FATFS *fs;
    DSTATUS stat;
    uint32_t crc32_val;

    /* Check validity of the parameters */
    if (drv >= _DRIVES) return FR_INVALID_DRIVE;

    /* Check mounted drive and clear work area */
    fs = FatFs[drv];
    if (!fs) return FR_NOT_ENABLED;
    fs->fs_type = 0;
    drv = LD2PD(drv);

    /* Get disk statics */
    stat = disk_initialize(drv);
    if (stat & STA_NOINIT) return FR_NOT_READY;
    if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;

    if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)
        return FR_MKFS_ABORTED;
    
    if (n_part > MAX_SECTOR) n_part = MAX_SECTOR;

    /* Pre-compute number of clusters and FAT type */
    // 这个保存在 FSI_Free_Count
    // n_clst = n_part / SS(fs);

    n_fat = BFFS_FAT_SIZE;             /* sectors per FAT */
    b_fat = 3;                         /* FATs start sector */
    b_dir = 1;                         /* Directory start sector */
    b_bmp = n_part/2+1;                /* bitmap start sector */
    b_data = b_bmp + 2;                /* journal start sector */

    /* Create FAT VBR */
    tbl = fs->win;                                   /* Clear buffer */
    mem_set(tbl, 0, SS(fs));
    mem_cpy(tbl + BPB_SYS_TAG, BPB_FS_TAG, 10);     /* signature */
    tbl[BPB_SYS_VER] = 0;
    ST_WORD(tbl+BPB_SYS_KPerClus, 64);               /* Cluster size [KB] */
    ST_DWORD(tbl+BPB_SYS_TotSec, n_part);            /* Number of total sectors */
    ST_DWORD(tbl+BPB_SYS_RootEntCnt, N_ROOTDIR);     /* Number of total sectors */
    ST_DWORD(tbl+BPB_SYS_UsedSec, n_part/2);         /* offset of journal sector */
    ST_DWORD(tbl+BPB_SYS_JnInfo, b_bmp);             /* offset of journal info sector */
    ST_DWORD(tbl+BPB_SYS_JnData, b_data);            /* offset of journal data sector */

    if (disk_write(drv, tbl, 0, 1) != RES_OK) return FR_DISK_ERR;    /* Write it to the VBR sector */

    /* Initialize FAT area */
    mem_set(tbl, 0xFF, SS(fs));
    crc32_val = bffs_crc32(fs->win, SS(fs)-4, 0);
    ST_DWORD(&fs->win[SS(fs)-4], crc32_val);

    for (m = 0; m < N_FATS; m++) {
        if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
            return FR_DISK_ERR;
        for (n = 1; n < n_fat; n++) {
            if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
                return FR_DISK_ERR;
        }
    }

    /* Initialize Root directory */
    if (disk_write(drv, tbl, b_dir, 1) != RES_OK)
        return FR_DISK_ERR;
    if (disk_write(drv, tbl, b_dir+1, 1) != RES_OK)
        return FR_DISK_ERR;

    /* Initialize bitmap sector */
    if (disk_eraser(drv, b_bmp) != RES_OK)
        return FR_DISK_ERR;

    /* Initialize bitmap sector */
    if (disk_eraser(drv, b_bmp+1) != RES_OK)
        return FR_DISK_ERR;

    /* Initialize first journal sector */
    if (disk_eraser(drv, b_data) != RES_OK)
        return FR_DISK_ERR;

    if (disk_ioctl(drv, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;

    return FR_OK;
}




/*-----------------------------------------------------------------------*/
/* Look up bitmap sector                                                 */
/*-----------------------------------------------------------------------*/
// 如果全是FF会怎样？如果全是00会怎样？
static uint32_t lookup_free_sector(void *bmp_buf, uint32_t len)
{
    uint32_t left,mid,right;
    uint8_t *pData = (uint8_t *)bmp_buf;
    left = 0;
    right = len/4+1;

    while(left < right) {
        mid = left + (right-left)/2;
        if (pData[mid] == 0xFF) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    if(right>0) right--;
    left = pData[right];
    mid = 0;
    while((left & 0x3) != 0x3 && mid<4) {
        left >>= 2;
        mid++;
    }
    if(mid == 0) mid=1;
    return right*4+mid-1;
}




/*-----------------------------------------------------------------------*/
/* Look up blank entry in current data sector                            */
/*-----------------------------------------------------------------------*/
// 8byte空闲就切换下一个扇区
#define JOURF_ALIGN_SIZE     8
static uint32_t lookup_valid_entry(void *data_buf, uint32_t len)
{
    uint32_t left,mid,right;
    uint8_t *pData = (uint8_t *)data_buf;
    const uint32_t item_size = JOURF_ALIGN_SIZE;
    
    left = 0;
    right = len/item_size - 1;

    while(left < right) {
        mid = left + (right-left)/2;
        if (*(uint32_t *)(pData+mid*item_size) == 0xFFFFFFFF) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    right *= item_size;
    if (right == 0) return right;
    while(pData[right] == 0xFF && right > 0) right--;
    return right+1;
}


/*-----------------------------------------------------------------------*/
/* Mount/Unmount a Logical Drive                                         */
/*-----------------------------------------------------------------------*/
FRESULT chk_mounted (
    const CHAR **path,    /* Pointer to pointer to the path name (drive number) */
    FATFS **rfs        /* Pointer to pointer to the found file system object */
)
{
    UINT vol;
    INT i;
    BYTE *tbl;
    DSTATUS stat;
    DWORD tsect;
    uint32_t cur_sect;
    // const CHAR *p = *path;
    FATFS *fs;
    JF_FILE *jfp = &journal_file;
    uint32_t crc32_val;
    (void)path;

    /* Get logical drive number to acquire FAT Object */
    // vol = get_ldnumber(&rp);
    vol = 0;
    fs = FatFs[vol];
    if (rfs != NULL) *rfs = fs;;
    if (!fs) return FR_NOT_ENABLED;    /* Is the file system object available? */

    ENTER_FF(fs);                    /* Lock file system */

    if (fs->fs_type) {                /* If the logical drive has been mounted */
        return FR_OK;
    }

    /* The logical drive must be mounted. Following code attempts to mount the volume */
    fs->fs_type = 0;                      /* Clear the file system object */
    fs->drive = vol;                      /* Bind the logical drive and a physical drive */
    stat = disk_initialize(fs->drive);    /* Initialize low level disk I/O layer */
    if (stat & STA_NOINIT)                /* Check if the drive is ready */
        return FR_NOT_READY;

    /* Load boot record and check it */
    if (disk_read(fs->drive, fs->win, 0, 1) != RES_OK) {
        return FR_DISK_ERR;
    }
    tbl = &fs->win[BPB_SYS_TAG];
    if (mem_cmp(tbl, BPB_FS_TAG, 8))
        return FR_NO_FILESYSTEM;

    fs->sects_fat = BFFS_FAT_SIZE;                                    /* Number of sectors per FAT */
    fs->n_fats = 2;                                       /* Number of FAT copies */
    fs->fatbase = 3;                                      /* FAT start sector (lba) */
    fs->csize = 16;                                       /* Number of sectors per cluster */
    fs->n_rootdir = LD_WORD(fs->win+BPB_SYS_RootEntCnt);  /* Number of root directory entries */
    if (fs->n_rootdir != N_ROOTDIR) return FR_NO_FILESYSTEM;
    tsect = LD_WORD(fs->win+BPB_SYS_UsedSec);              /* Number of sectors on the volume */
    
    fs->max_clust = (tsect - 16) / fs->csize;

    fs->dirbase = 1;                                    /* Root directory start sector (lba) */
    fs->database = 16;                                    /* Data start sector (lba) */
    fs->wflag = 0;
    
    fs->fs_type = 1;
    fs->winsect = 0;                                     /* Invalidate sector cache */

    jfp->bmp_base = LD_WORD(fs->win+BPB_SYS_JnInfo);
    jfp->first_sect = LD_WORD(fs->win+BPB_SYS_JnData);
    jfp->last_sect = LD_WORD(fs->win+BPB_SYS_TotSec) - 1;
    jfp->flag = 0;
    jfp->ofs_sect = 0;
    jfp->fptr = 0;

    /* verify root directory integrity */
    tbl = fs->win;
    if (disk_read(fs->drive, tbl, fs->dirbase, 1) != RES_OK) {
        return FR_DISK_ERR;
    }
    crc32_val = bffs_crc32(tbl, SS(fs)-4, 0);
    if (crc32_val != LD_DWORD(&tbl[SS(fs)-4])) {
        LOGE("The root directory CRC verification failed");
        if (disk_read(fs->drive, tbl, fs->dirbase+1, 1) != RES_OK) {
            return FR_DISK_ERR;
        }
        crc32_val = bffs_crc32(tbl, SS(fs)-4, 0);
        if (crc32_val != LD_DWORD(&tbl[SS(fs)-4])) return FR_DISK_ERR;
        if (disk_write(fs->drive, tbl, fs->dirbase, 1) != RES_OK)
            return FR_DISK_ERR;
        LOGE("The root directory was repaired successfully");
    }


    /* verify FAT entry integrity */
    if (disk_read(fs->drive, tbl, fs->fatbase, 1) != RES_OK) {
        return FR_DISK_ERR;
    }
    crc32_val = bffs_crc32(tbl, SS(fs)-4, 0);
    if (crc32_val != LD_DWORD(&tbl[SS(fs)-4])) {
        LOGE("The FAT entry CRC verification failed");
        if (disk_read(fs->drive, tbl, fs->fatbase+fs->sects_fat, 1) != RES_OK) {
            return FR_DISK_ERR;
        }
        crc32_val = bffs_crc32(tbl, SS(fs)-4, 0);
        if (crc32_val != LD_DWORD(&tbl[SS(fs)-4])) return FR_DISK_ERR;
        if (disk_write(fs->drive, tbl, fs->fatbase, 1) != RES_OK)
            return FR_DISK_ERR;
        LOGE("The FAT entry was repaired successfully");
    }

    /* obtain the metadata of the log file */
    if (disk_read(fs->drive, fs->win, fs->dirbase, 1) != RES_OK) {
        return FR_DISK_ERR;
    }

    jfp->ofs_sect = lookup_free_sector(fs->win, jfp->last_sect - jfp->first_sect);
    cur_sect = jfp->ofs_sect + jfp->first_sect;

    // 然后查找当前扇区的有效数据，每次写入32byte
    if (disk_read(fs->drive, fs->win, cur_sect, 1) != RES_OK) {
        return FR_DISK_ERR;
    }
    // 查找第一个空条目(0xFF), 至少有32byte的 0xFFFFFFFF
    tbl = fs->win + SS(fs) - JOURF_ALIGN_SIZE;
    for(i=JOURF_ALIGN_SIZE - 1; i>=0; i--) {
        if(tbl[i] == 0xFF) continue;
    }

    if (i == -1) {
        jfp->fptr = lookup_valid_entry(fs->win, SS(fs));
    } else {
        jfp->fptr = 0;
        // 有可能越界
        jfp->ofs_sect++;
    }

    return FR_OK;
}
